package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    //微信服务接口地址

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private UserMapper userMapper;
    @Override
    public Result<UserLoginVO> login(UserLoginDTO dto) {


        //调用微信小程序接口，换取用户的openid
        String openId = getOpenId(dto.getCode());

        //根据openid查询用户信息，如果查不到，说明是新用户，保存入库
        User user= userMapper.selectByOpenId(openId);
        if(user==null){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.save(user);
        }
        //如果查询到，根据id生成token，返回给前端
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);


        //获取商家信息
        Merchant merchant = merchantMapper.getById(1L);
        //计算费用
        String lnglat = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal cost = MapUtils.getDelivoryCost(lnglat, dto.getLocation());

        //5.构造返回结果
        UserLoginVO loginVO = UserLoginVO.builder().token(token)
                .shopTelephone(merchant.getShopTelephone())
                .shopName(merchant.getShopName())
                .shopAddress(merchant.getShopAddress())
                .deliveryFee(cost)
                .shopId(merchant.getId())
                .openid(openId)
                .build();

        return Result.success(loginVO);
    }

    private String getOpenId(String code) {
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String jsonStr =  HttpClientUtil.doGet(WX_LOGIN,map);
        Map res = JSON.parseObject(jsonStr, Map.class);
        return res.get("openid").toString();
    }

}
